package com.hn.project.rqinspect.controller;

import com.hn.common.enums.RoleTypeEnum;
import com.hn.common.utils.SecurityUtils;
import com.hn.doc.xyj.annotation.Api;
import com.hn.framework.web.controller.BaseController;
import com.hn.framework.web.domain.AjaxResult;
import com.hn.framework.web.page.TableDataInfo;
import com.hn.project.rqinspect.domain.database.UserBranch;
import com.hn.project.rqinspect.domain.dto.TaskRecordHistoryDto;
import com.hn.project.rqinspect.domain.vo.TaskRecordVo;
import com.hn.project.rqinspect.service.TaskService;
import com.hn.project.rqinspect.service.UserBranchService;
import com.hn.project.rqinspect.service.UserGroupService;
import com.hn.utils.AssertUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * 报表
 */
@Api("报表")
@RequestMapping("report")
@RestController
public class ReportController extends BaseController {

    @Autowired
    private TaskService taskService;

    @Autowired
    private UserGroupService userGroupService;

    @Autowired
    private UserBranchService userBranchService;

    /**
     * 任务记录列表
     * - 历史记录
     */
    @Api(value = "历史巡检记录", result = TaskRecordHistoryDto.class)
    @GetMapping("listHistoryTaskRecord")
    public TableDataInfo listHistoryTaskRecord(TaskRecordVo taskRecordVo) {
        if (taskRecordVo.getBranchId() == null) {
            Integer roleType = taskRecordVo.getRoleType();
            AssertUtils.notNull(roleType, "roleType 必传");
            Integer userId = SecurityUtils.getUserId();
            if (RoleTypeEnum.BRANCH.type.equals(roleType)) {
                // 获取管理的网点
                List<Integer> branchIds = userBranchService.listBranchIdsByUserId(userId);
                if (branchIds == null || branchIds.isEmpty()) {
                    return getDataTable(new ArrayList<>());
                }

                List<Integer> taskIds = taskService.listTaskIdsByBranchIds(branchIds);
                if (taskIds == null || taskIds.isEmpty()) {
                    return getDataTable(new ArrayList<>());
                }
                taskRecordVo.setTaskIds(taskIds);
            } else {
                // 巡检干部
                taskRecordVo.setUserId(userId);
            }
        }
        startPage();
        return getDataTable(taskService.listHistoryTaskRecord(taskRecordVo));
    }

    @Api(value = "巡检日记详情", result = TaskRecordHistoryDto.class)
    @GetMapping("getHistoryTaskRecord")
    public AjaxResult getHistoryTaskRecord(Integer taskRecordId) {
        AssertUtils.notNull(taskRecordId, "请先选择巡检日记");
        return AjaxResult.success(taskService.getHistoryTaskRecord(taskRecordId));
    }

}
